/**
 * 目录管理器
 */
class DirectoryManager {
    constructor() {
        this.directoriesList = document.getElementById('directoriesList');
        this.directoryPath = document.getElementById('directoryPath');
        this.addDirectoryBtn = document.getElementById('addDirectoryBtn');
        this.init();
    }

    init() {
        if (this.addDirectoryBtn) {
            this.addDirectoryBtn.addEventListener('click', () => this.addDirectory());
        }

        // 为删除和切换状态按钮添加全局事件委托
        document.addEventListener('click', (e) => {
            if (e.target.closest('[onclick*="removeDirectory"]')) {
                e.preventDefault();
                const button = e.target.closest('button');
                const directoryId = this.extractDirectoryId(button);
                if (directoryId) {
                    this.removeDirectory(directoryId);
                }
            } else if (e.target.closest('[onclick*="toggleDirectoryStatus"]')) {
                e.preventDefault();
                const button = e.target.closest('button');
                const { directoryId, currentStatus } = this.extractToggleData(button);
                if (directoryId !== null) {
                    this.toggleDirectoryStatus(directoryId, currentStatus);
                }
            }
        });
    }

    async loadDirectoriesList() {
        if (!this.directoriesList) return;

        this.directoriesList.innerHTML = '<div class="text-center py-4"><i class="fas fa-spinner fa-spin mr-2"></i>加载中...</div>';
        
        try {
            const response = await window.apiClient.getDirectories();
            
            if (response.success) {
                this.displayDirectoriesList(response.data);
            } else {
                this.directoriesList.innerHTML = `<div class="text-red-500 py-4">加载失败: ${response.message}</div>`;
            }
        } catch (error) {
            console.error('Error loading directories:', error);
            this.directoriesList.innerHTML = '<div class="text-red-500 py-4">加载失败，请检查服务器连接</div>';
        }
    }

    displayDirectoriesList(directories) {
        if (!this.directoriesList) return;

        if (directories.length === 0) {
            this.directoriesList.innerHTML = '<div class="text-gray-600 py-4">暂无索引目录</div>';
            return;
        }
        
        const directoriesHtml = directories.map(dir => this.buildDirectoryItemHtml(dir)).join('');
        this.directoriesList.innerHTML = directoriesHtml;
    }

    buildDirectoryItemHtml(dir) {
        return `
            <div class="border border-gray-200 rounded-lg p-4 mb-3 hover:shadow-md transition-shadow" data-directory-id="${dir.id}">
                <div class="flex justify-between items-start mb-2">
                    <h5 class="font-bold text-gray-800">${dir.path}</h5>
                    <div class="flex space-x-2">
                        <button class="text-blue-600 hover:text-blue-800" data-action="toggle" data-directory-id="${dir.id}" data-current-status="${dir.enabled}">
                            <i class="fas ${dir.enabled ? 'fa-toggle-on' : 'fa-toggle-off'}"></i>
                        </button>
                        <button class="text-red-600 hover:text-red-800" data-action="remove" data-directory-id="${dir.id}">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                </div>
                <div class="text-sm text-gray-600 mb-2">
                    <span>状态: <span class="${dir.enabled ? 'text-green-600' : 'text-gray-500'}">${dir.enabled ? '已启用' : '已禁用'}</span></span>
                    <span class="ml-4">文件数: ${dir.file_count || 0}</span>
                </div>
                <div class="text-xs text-gray-500">
                    <span>创建时间: ${new Date(dir.created_at).toLocaleString()}</span>
                    <span class="ml-4">更新时间: ${new Date(dir.updated_at).toLocaleString()}</span>
                </div>
            </div>
        `;
    }

    async addDirectory() {
        const directoryPath = this.directoryPath?.value.trim();
        
        if (!directoryPath) {
            this.showAlert('请输入目录路径');
            return;
        }
        
        this.setAddButtonLoading(true);
        
        try {
            const response = await window.apiClient.addDirectory(directoryPath);
            
            if (response.success) {
                // 清空输入框
                if (this.directoryPath) {
                    this.directoryPath.value = '';
                }
                
                // 重新加载目录列表
                await this.loadDirectoriesList();
                
                this.showAlert('目录添加成功');
            } else {
                this.showAlert(`添加失败: ${response.message}`);
            }
        } catch (error) {
            console.error('Error adding directory:', error);
            this.showAlert('添加失败，请检查服务器连接');
        } finally {
            this.setAddButtonLoading(false);
        }
    }

    async removeDirectory(directoryId) {
        if (!confirm('确定要删除此目录吗？删除后将无法恢复相关索引数据。')) {
            return;
        }
        
        try {
            const response = await window.apiClient.removeDirectory(directoryId);
            
            if (response.success) {
                // 重新加载目录列表
                await this.loadDirectoriesList();
                
                this.showAlert('目录删除成功');
            } else {
                this.showAlert(`删除失败: ${response.message}`);
            }
        } catch (error) {
            console.error('Error removing directory:', error);
            this.showAlert('删除失败，请检查服务器连接');
        }
    }

    async toggleDirectoryStatus(directoryId, currentStatus) {
        try {
            const response = await window.apiClient.toggleDirectoryStatus(directoryId, !currentStatus);
            
            if (response.success) {
                // 重新加载目录列表
                await this.loadDirectoriesList();
            } else {
                this.showAlert(`状态更新失败: ${response.message}`);
            }
        } catch (error) {
            console.error('Error toggling directory status:', error);
            this.showAlert('状态更新失败，请检查服务器连接');
        }
    }

    setAddButtonLoading(loading) {
        if (!this.addDirectoryBtn) return;

        if (loading) {
            this.addDirectoryBtn.disabled = true;
            this.addDirectoryBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>添加中...';
        } else {
            this.addDirectoryBtn.disabled = false;
            this.addDirectoryBtn.innerHTML = '<i class="fas fa-plus mr-2"></i>添加目录';
        }
    }

    extractDirectoryId(button) {
        // 从按钮的onclick属性或data属性中提取目录ID
        const directoryElement = button.closest('[data-directory-id]');
        return directoryElement ? directoryElement.getAttribute('data-directory-id') : null;
    }

    extractToggleData(button) {
        // 从按钮的onclick属性或data属性中提取目录ID和当前状态
        const directoryElement = button.closest('[data-directory-id]');
        if (!directoryElement) return { directoryId: null, currentStatus: false };

        const directoryId = directoryElement.getAttribute('data-directory-id');
        const currentStatus = button.getAttribute('data-current-status') === 'true';
        
        return { directoryId, currentStatus };
    }

    showAlert(message) {
        alert(message);
    }
}

// 创建全局目录管理器实例
window.directoryManager = new DirectoryManager();